package com.guanzi.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guanzi.server.entity.User;
import com.guanzi.server.entity.dto.UserSaveDTO;
import com.guanzi.server.mapper.UserMapper;
import com.guanzi.server.service.IUserService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author guanzi
 * @since 2021-06-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    /**
     * 已存在的用户，即登录
     * @param username
     * @return
     */
    @Override
    public User login(String username) {
        if ( null == username ) {
            return null;
        }
        User user = baseMapper.selectOne(new QueryWrapper<User>().eq("username",username));
        if ( null == user ) {
            return null;
        }
        //写入本次登录时间
        user.setLoginTime(LocalDateTime.now());
        baseMapper.updateById(user);
        return user;
    }

    /**
     * 不存在的用户，则注册并登录
     * @param username
     * @return
     */
    @Override
    public User register(String username) {
        if ( null == username ) {
            return null;
        }
        User user = new User();
        user.setUsername(username);
        user.setImg("404.jpg");
        user.setIsDel(0);
        int insert = this.baseMapper.insert(user);
        if ( insert < 0 ) {
            return null;
        }
        //手动登录，获取自增的id，以备不时之需
        User login = login(username);
        return login;
    }

    /**
     * 得到所有user列表
     * @return
     */
    @Override
    public List<User> getUserList() {
        return baseMapper.selectList(null);
    }

    /**
     * 删除用户(单个)
     * @param id
     */
    @Override
    public void deleteUser(Integer id) {
        baseMapper.deleteById(id);
    }

    /**
     * 用户图片保存
     * @param userSaveDTO
     */
    @Override
    public Boolean updateUser(UserSaveDTO userSaveDTO) {
        User user = baseMapper.selectById( userSaveDTO.getId() );

        // 查询名称是否被使用
        User temp = baseMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if ( temp != null && !(temp.getId().equals(user.getId())) ) {
            return false;
        }

        user.setUsername( userSaveDTO.getUsername() );
        user.setImg( userSaveDTO.getImg() );
//        user.setPassword( userSaveDTO.getPassword() );
        baseMapper.updateById(user);
        return true;
    }




}
